package com.unohacha.qqj.fzdr.main;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.MainActivity;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.adapter.NineGridViewClickAdapter2;
import com.unohacha.qqj.fzdr.bean.find.DefaultFindBean;
import com.unohacha.qqj.fzdr.bean.find.FindListBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.FilterPopwindow;
import com.unohacha.qqj.mylibrary.base.BaseFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

/**
 * 发现碎片
 */
public class FindFragment extends BaseFragment implements OnRefreshLoadmoreListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.line_supply)
    TextView lineSupply;
    @BindView(R.id.common_title2)
    TextView commonTitle2;
    @BindView(R.id.line_need)
    TextView lineNeed;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;

    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.supply_find_rl)
    RelativeLayout supplyFindRl;
    @BindView(R.id.need_find_rl)
    RelativeLayout needFindRl;
    @BindView(R.id.pt_line)
    ImageView ptLine;
    @BindView(R.id.title_find)
    TextView title_find;//发现的二级标题
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private FilterPopwindow filterPopwindow;//筛选弹窗
    private MainActivity mActivity;
    private int last_page = 1;//最大页数
    private int type = 1;//类型
    private DefaultFindBean findBean;
    private int page = 1;//当前页数
    private String address_id = "12685";//定位后的或者选择后的地址id ,默认先写余杭区
    private List<FindListBean.DataEntity> mFindList = new ArrayList<>();
    private List<FindListBean.DataEntity.DataTwo> mFindDataTwoList = new ArrayList<>();
    private String keywors = "";//关键词
    private BaseRVAdapter mBaseAdapter;
    private int supply_cate_id;//标签的id

    @Override
    protected void initBundle(Bundle arguments) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_find_layout;
    }

    @Override
    protected void initView(View rootView) {
        mActivity = (MainActivity) getActivity();
        commonRightImage.setVisibility(View.GONE);
        commonBack.setVisibility(View.VISIBLE);
        commonBack.setImageResource(R.drawable.search);
        commonRightText.setVisibility(View.VISIBLE);
        commonRightText.setText("筛选");
        if (!TextUtils.isEmpty(Prefer.getInstance().obtainReLocation(getContext()))){
            address_id = Prefer.getInstance().obtainReLocation(getContext());
        }else {
            address_id = "12685";//定位后的或者选择后的地址id ,默认先写余杭区
        }
        initTabLayout();
    }

    private void initTabLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));
        carListRecycler.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayout.VERTICAL,false));
        getDefaultFind();
    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.common_back,R.id.need_find_rl,R.id.supply_find_rl,
              R.id.common_right_text})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.common_back://搜索

                break;
            case R.id.need_find_rl://需求发现
                type = 2;
                lineSupply.setVisibility(View.INVISIBLE);
                lineNeed.setVisibility(View.VISIBLE);

                commonTitle.setTextColor(getResources().getColor(R.color.text_black_666));
                commonTitle2.setTextColor(getResources().getColor(R.color.black));
                getDefaultFind();
                break;
            case R.id.supply_find_rl://供应发现
                type = 1;
                lineSupply.setVisibility(View.VISIBLE);
                lineNeed.setVisibility(View.INVISIBLE);
                commonTitle.setTextColor(getResources().getColor(R.color.text_black_666));
                commonTitle2.setTextColor(getResources().getColor(R.color.black));
                commonTitle.setTextColor(getResources().getColor(R.color.black));
                commonTitle2.setTextColor(getResources().getColor(R.color.text_black_666));
                getDefaultFind();
                break;
            case R.id.common_right_text://筛选
                filterPopwindow = new FilterPopwindow(mActivity,mActivity);
                filterPopwindow.showUi();
                if (Build.VERSION.SDK_INT < 24) {
                    filterPopwindow.showAsDropDown(supplyFindRl);
                } else {
                    int[] location = new int[2];
                    supplyFindRl.getLocationOnScreen(location);
                    int x = location[0];
                    int y = location[1];
                    filterPopwindow.showAtLocation(supplyFindRl, Gravity.NO_GRAVITY, x, y + view.getHeight());
                }

                filterPopwindow.setOnPackUpListener(new FilterPopwindow.OnPackUpListener() {
                    @Override
                    public void onPackUp() {
                        //收起的方法
                    }

                    @Override
                    public void onGetPositionData(int id, String name) {
                        mActivity.MyToast("" + name );
                        supply_cate_id = id;
                        page = 1;
                        getFindList(supply_cate_id,"",address_id);
                        title_find.setText(name);
                    }

                });
                break;
        }
    }

    //默认是供应还是需求
    private void getDefaultFind(){
        Map<String,Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        XUtil.Post(UrlConfig.DEFAULT_FIND,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                mRefreshLayout.finishRefresh();
                mRefreshLayout.resetNoMoreData();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))){
                        Gson gson = new Gson();
                        findBean = gson.fromJson(result,DefaultFindBean.class);
                        if (null != findBean){
                            if (0 == supply_cate_id) {
                                supply_cate_id = findBean.getData().getSupply_cate_id();
                                title_find.setText(findBean.getData().getTitle());
                            }
                            getFindList(supply_cate_id,"",address_id);
                        }
                    }else {
                        mActivity.MyToast(jsonObject.optString("message"));
                    }
                    mRefreshLayout.finishLoadmore();
                    mRefreshLayout.finishLoadmoreWithNoMoreData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //根据 类型id：typeid 标签id：supply_cate_id
    private void getFindList(int id, String keyword, String address_id){
        Map<String,Object> params = new HashMap<>();
        params.put("token",Prefer.getInstance().getToken());
        params.put("typeid",type);//1-供应 2-需求
        params.put("supply_cate_id",id);//分类id
        params.put("keyword",keyword);//搜索关键字
        params.put("address_id",address_id);//地区id
        params.put("page",page);
        Set<String> set = params.keySet();
        for (String s : set) {
            Log.d(TAG, s+" : "+params.get(s));
        }
        XUtil.Post(UrlConfig.FIND_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG: " ,result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))){
                        Gson gson = new Gson();
                        FindListBean findListBean = gson.fromJson(result,FindListBean.class);
                        if (null != findListBean){
                            if (0 != mFindList.size()){
                               mFindList.clear();
                            }
                            if (0 != mFindDataTwoList.size()){
                                mFindDataTwoList.clear();
                            }
                            last_page = findListBean.getData().getLast_page();
                            if (page == 1){
                                mFindList.add(findListBean.getData());
                                mFindDataTwoList.addAll(findListBean.getData().getData());
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }

                            setFindApapter();
                        }
                    }else if ("100".equals(jsonObject.optString("code"))){
                        mActivity.MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        mActivity.MyToast(jsonObject.optString("message"));
                        if (page == 1){
                            if (null != mFindDataTwoList){
                                mFindDataTwoList.clear();
                            }
                            if (null != mFindList){
                                mFindList.clear();
                            }
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            mBaseAdapter.notifyDataSetChanged();
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置发现列表的数据
    private void setFindApapter(){

        mBaseAdapter = new BaseRVAdapter(mActivity,mFindDataTwoList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_find_need_or_supply;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                final int tagPosition = position;
                RelativeLayout rl_user = holder.getView(R.id.rl_user);
                ImageView store_logo_iv = holder.getImageView(R.id.store_logo_iv);//头像
                TextView store_name_tv = holder.getTextView(R.id.store_name_tv);//名字
                TextView store_report_content = holder.getTextView(R.id.store_report_content);//发表的内容
                TextView report_time_tv = holder.getTextView(R.id.report_time_tv);//发表的时间
                TextView look_num_tv = holder.getTextView(R.id.look_num_tv);//浏览的数量
                TextView comment_num_tv = holder.getTextView(R.id.comment_num_tv);//评论的数量
                TextView collect_num_tv = holder.getTextView(R.id.collect_num_tv);//收藏的数量
                TextView get_message_tv = holder.getTextView(R.id.get_message_tv);//获取信息
                LinearLayout user_a_ll = holder.getView(R.id.user_a_ll);//用户a
                LinearLayout user_b_ll = holder.getView(R.id.user_b_ll);//用户b
                TextView user_a = holder.getTextView(R.id.user_a);//用户a姓名
                TextView user_comment_a = holder.getTextView(R.id.user_comment_a);//用户a 评论
                TextView user_b = holder.getTextView(R.id.user_b);//用户b姓名
                TextView user_comment_b = holder.getTextView(R.id.user_comment_b);//用户b 评论

                get_message_tv.setVisibility(View.GONE);
                List<FindListBean.DataEntity.DataTwo.SupplyData> mSupplyList = new ArrayList<>();
                mSupplyList = mFindDataTwoList.get(position).getSupply();
                if (0 != mSupplyList.size()){//评论的内容不为空
                    rl_user.setVisibility(View.VISIBLE);
                    if (mSupplyList.size() <= 1){
                        user_a_ll.setVisibility(View.VISIBLE);
                        user_b_ll.setVisibility(View.GONE);
                        user_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getMember_no() + ": ");
                        user_comment_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getContent());
                    }else {
                        user_a_ll.setVisibility(View.VISIBLE);
                        user_b_ll.setVisibility(View.VISIBLE);
                        user_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getMember_no() + ": ");
                        user_comment_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getContent());
                        user_b.setText(mFindDataTwoList.get(position).getSupply().get(1).getMember_no() + ": ");
                        user_comment_b.setText(mFindDataTwoList.get(position).getSupply().get(1).getContent());
                    }
                }else {
                    rl_user.setVisibility(View.GONE);
                }
                look_num_tv.setText(mFindDataTwoList.get(position).getHits() + " 浏览");
                comment_num_tv.setText(mFindDataTwoList.get(position).getCommon_nums() + " 评论");
                collect_num_tv.setText(mFindDataTwoList.get(position).getCollection_count() + " 收藏");
                Glide.with(mActivity).load(mFindDataTwoList.get(position).getMember_thumb())
                        .error(R.drawable.ic_default_photo).into(store_logo_iv);
                store_name_tv.setText(mFindDataTwoList.get(position).getMember_no());
                store_report_content.setText(mFindDataTwoList.get(position).getTitle());
                report_time_tv.setText(mFindDataTwoList.get(position).getCreate_time());
                get_message_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO: 2018/5/24 0024 查看信息
                        mActivity.MyToast("查看信息");
                    }
                });

                //九宫格展示
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                List<String> imageDetails = mFindDataTwoList.get(position).getList_pic();
                if (imageDetails != null) {
                    for (String imageDetail : imageDetails) {
                        ImageInfo info = new ImageInfo();
                        info.setThumbnailUrl(imageDetail);
                        info.setBigImageUrl(imageDetail);
                        imageInfo.add(info);
                    }
                }

                NineGridView mRecyclerView = holder.getView(R.id.mRecyclerView);//图片的列表 3 列
                if (!TextUtils.isEmpty(mFindDataTwoList.get(position).getWidth())
                        && !TextUtils.isEmpty(mFindDataTwoList.get(position).getHeight())) {
                    float wh = Float.valueOf(mFindDataTwoList.get(position).getWidth())
                            /Float.valueOf(mFindDataTwoList.get(position).getHeight());
                    mRecyclerView.setSingleImageRatio(wh);
                }else {
                    mRecyclerView.setSingleImageSize(500);
                }
                mRecyclerView.setAdapter(new NineGridViewClickAdapter2(mContext, imageInfo));

            }
        };
        
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Intent intent = new Intent(getActivity(),FindDetailActivity2.class);
                intent.putExtra("typeid",supply_cate_id);
                intent.putExtra("id",mFindDataTwoList.get(position).getId());
                startActivity(intent);
            }
        });
        carListRecycler.setAdapter(mBaseAdapter);
        mBaseAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        if (page < last_page) {
            refreshlayout.getLayout().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != findBean) {
                        page ++;
                        getFindList(supply_cate_id,keywors,address_id);
                    }

                }
            },2000);
        }else {
            mActivity.MyToast(getResources().getString(R.string.last_page));
            mRefreshLayout.finishLoadmore();
            mRefreshLayout.finishLoadmoreWithNoMoreData();
            return;
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != findBean) {
                    page = 1;
                    getFindList(supply_cate_id,keywors,address_id);
                }
            }
        },2000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != filterPopwindow){
            filterPopwindow.dismissView();
        }
    }
}
